<script lang="ts" setup name="LoginForm">
//-----------------------登录表单功能-----------------------------
import { ref, watch } from 'vue'
import Message from '@/components/message/index'
import useStore from '@/store/index'
import { useRouter } from 'vue-router'
import { useField , useForm } from 'vee-validate' //插件
import { useCountDown } from '@/utils/hooks'
import {
  accountRule,
  mobileRule,
  codeRule,
  passwordRule,
  isAgreeRule
} from '@/utils/validate'
const type = ref<'account' | 'mobile'>('account')
const { user } = useStore()
const router = useRouter()

const { validate, resetForm } = useForm({
  // 设置初始值
  initialValues:{
   mobile: '13012345678',
    code: '123456',
    account: 'cdshi0006',
    password: '123456',
    isAgree: true,
  },
  // 设置校验规则
   validationSchema: {
    account: accountRule,
    mobile: mobileRule,
    code: codeRule,
    password: passwordRule,
    isAgree: isAgreeRule
  },
  // validationSchema:{
  //   account(value:string){
  //     if(!value) return '不能为空'
  //      // 校验2: 6-20个字符, 必须以字母开头 正则
  //     if (!/^[a-zA-Z]\w{5,19}$/.test(value)) return '必须是字母开头的6-20个字符'
  //     // 如果校验通过, 需要 return true, 其他所有情况, 都是失败
  //     return true
  //   },
  //   password(value:string){
  //     if(!value) return '密码不能为空'
  //     return true
  //   },
  //   isAgree(value:boolean){
  //     if(!value) return '请勾选'
  //     return true
  //   },
  //    mobile(value: string) {
  //     if (!value) return '请输入手机号'
  //     if (!/^1[3-9]\d{9}$/.test(value)) return '手机号格式有误'
  //     return true
  //   },
  //   code(value: string) {
  //     if (!value) return '请输入验证码'
  //     if (!/^\d{6}$/.test(value)) return '验证码格式有误'
  //     return true
  //   },
  // }
})
// value: 用于和表单绑定的响应式数据 v-model="value"
// errorMessage: 错误信息提示, 用于实时展示 <div>errorMessage</div>
 const{value:account,errorMessage:accountError}= useField<string>('account')
 const{value:password,errorMessage:passwordError}= useField<string>('password')
 const{value:isAgree,errorMessage:isAgreeError}= useField<boolean>('isAgree')
 const{value:mobile,
  errorMessage:mobileError,
  validate: validateMobile,
 }= useField<string>('mobile')
 const{value:code,errorMessage:codeError}= useField<string>('code')

//--------------------------------------------------------------------------
//登录逻辑
const login = async () => {
 //登录前校验
 const res = await validate()
//  console.log(res);
//  if(!res.valid) return  Message.error('登录失败')
if(type.value === 'account'){  //如果是用户名登录
  //如果错误消息里没有用户名，密码，复选框就发请求
  if(res.errors.account || res.errors.password || res.errors.isAgree)return
   await user.login(account.value, password.value)
  
}else{  //短信验证登录
  if(res.errors.code || res.errors.mobile || res.errors.isAgree)return
    await user.mobileLogin(mobile.value,code.value)
}
    Message.success('恭喜, 登录成功')
    router.push('/')
}
//切换重置表单
watch(type,()=>{
// 一旦触发, 说明切换了, 直接重置表单
  resetForm()
})
//--------------------------------------------------------------------------
//验证码倒计时
// let timeId:number=-1 
// const time = ref(0)
const { time, start } =useCountDown(30) //封装的方法
//处理发送验证码逻辑
const mobileRef = ref<HTMLInputElement | null>(null)
const send=async()=>{
 const res = await validateMobile()
  if (time.value > 0) return //节流阀
// 手机号通过校验, 校验结果为 true 才发送验证码
 if(!res.valid){
   mobileRef.value?.focus()
    return
 }
 //发送请求
 await user.sendMobileCode(mobile.value)
  Message.success('获取验证码成功')
// --------------------------------------------------------------------------
  start()
  //开启倒计时
  // time.value=5
  // timeId = window.setInterval(()=>{
  //   time.value--
  //   if(time.value===0){
  //     clearInterval(timeId)
  //   }
  // },1000)
}
// --------------------------------------------------------------------------
//提供数据，用于收集表单数据
// const form = ref({
//   account: '',
//   password: '',
//   isAgree: false,
// })
//简单的一个非空检验。
 // if (form.value.account === '') {
  //   Message({ type: 'error', text: '用户名或手机号不能为空' })
  //   return
  // }
  // if (form.value.password === '') {
  //   Message({ type: 'error', text: '密码不能为空' })
  //   return
  // }
  // if (!form.value.isAgree) {
  //   Message({ type: 'error', text: '请同意许可' })
  //   return
  // }
    //   try {
    // } catch (e) {
    //   Message.error('用户名或者密码错误')
    // }
</script>




<template>
  <div class="account-box">
    <div class="toggle">
         <a href="javascript:;" @click="type = 'account'" v-if="type === 'mobile'">
        <i class="iconfont icon-user"></i> 使用账号登录
      </a>
       <a href="javascript:;" @click="type = 'mobile'" v-else>
        <i class="iconfont icon-msg"></i> 使用短信登录
      </a>
    </div>
    <div class="form">
        <template v-if="type === 'account'">
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input v-model="account" type="text" placeholder="请输入用户名" />
          </div>
          <!-- 错误提示 -->
          <div class="error" v-if="accountError">
          <i class="iconfont icon-warning" />{{accountError}}</div>
          </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-lock"></i>
            <input   v-model="password" type="password" placeholder="请输入密码" />
          </div>
           <div class="error" v-if="passwordError">
            <i class="iconfont icon-warning" />{{ passwordError }}
          </div>
        </div>
      </template>
      <template v-else>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-user"></i>
            <input ref="mobileRef" v-model="mobile" type="text" placeholder="请输入手机号" />
          </div>
           <div class="error" v-if="mobileError">
            <i class="iconfont icon-warning" />{{ mobileError }}
          </div>
        </div>
        <div class="form-item">
          <div class="input">
            <i class="iconfont icon-code"></i>
            <input v-model="code"  type="text" placeholder="请输入验证码" />
            <span class="code" @click="send">
            {{time>0?`${time}s后重新发送`:'发送验证码'}}</span>
          </div>
           <div class="error" v-if="codeError">
            <i class="iconfont icon-warning" />{{ codeError }}
          </div>
        </div>
      </template>
      <div class="form-item">
        <div class="agree">
         <!-- 复选框 -->
         <XtxCheckbox v-model="isAgree" />
          <span>我已同意</span>
          <a href="javascript:;">《隐私条款》</a>
          <span>和</span>
          <a href="javascript:;">《服务条款》</a>
        </div>
         <div class="error" v-if="isAgreeError">
          <i class="iconfont icon-warning" />{{ isAgreeError }}
        </div>
      </div>
      <a href="javascript:;" class="btn" @click="login">登录</a>
    </div>
    <div class="action">
      <!-- <img
        src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
        alt=""
      /> -->
      <a
      href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&amp;response_type=token&amp;scope=all&amp;redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback"
      ><img
      src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png"
      alt="QQ登录"
      border="0"
      /></a>
      <div class="url">
        <a href="javascript:;">忘记密码</a>
        <a href="javascript:;">免费注册</a>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
// 账号容器
.account-box {
  .toggle {
    padding: 15px 40px;
    text-align: right;
    a {
      color: @xtxColor;
      i {
        font-size: 14px;
      }
    }
  }
  .form {
    padding: 0 40px;
    &-item {
      margin-bottom: 28px;
      .input {
        position: relative;
        height: 36px;
        > i {
          width: 34px;
          height: 34px;
          background: #cfcdcd;
          color: #fff;
          position: absolute;
          left: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 18px;
        }
        input {
          padding-left: 44px;
          border: 1px solid #cfcdcd;
          height: 36px;
          line-height: 36px;
          width: 100%;
          &.error {
            border-color: @priceColor;
          }
          &.active,
          &:focus {
            border-color: @xtxColor;
          }
         
        }
        .code {
          font-size: 12px !important;
          position: absolute;
          right: 1px;
          top: 1px;
          text-align: center;
          line-height: 34px;
          font-size: 14px;
          background: #f5f5f5;
          color: #666;
          width: 90px;
          height: 34px;
          cursor: pointer;
        }
      }
      > .error {
        position: absolute;
        font-size: 12px;
        line-height: 28px;
        color: @priceColor;
        i {
          font-size: 14px;
          margin-right: 2px;
        }
      }
    }
    .agree {
      a {
        color: #069;
      }
    }
    .btn {
      display: block;
      width: 100%;
      height: 40px;
      color: #fff;
      text-align: center;
      line-height: 40px;
      background: @xtxColor;
      &.disabled {
        background: #cfcdcd;
      }
    }
  }
  .action {
    padding: 20px 40px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    img {
      cursor: pointer;
    }
    .url {
      a {
        color: #999;
        margin-left: 10px;
      }
    }
  }
}
</style>

